import {
	setRegionList,
	setUserAddressList,
	setMyOrderListData,
	setShouldRefreshMyOrderList,
	//
	UPLOAD_AVATAR,
	UODATE_MEMBER,
	//
	GET_USER_SERVICE_PROTOCOL,
	//
	GET_REGION_LIST,
	GET_USER_ADDRESS_LIST,
	ADD_DELETE_USER_ADDRESS,
	UPDATE_USER_ADDRESS,
	LOAD_MY_ORDER_LIST,
	LOAD_MY_ORDER_DETAIL,
	USER_CONFIRM_RECERVE_ORDER,
	//
	ADD_WX_SUBSCRIBE_MESSAGE,
	INSERT_SHOP_COMMENT,
	LOAD_INTEGRAL_LIST,
} from './actions';

import store from '../../index';

const prefixUrl = () => uni.$http.userPrefixUrl;
const shopPrefixUrl = () => uni.$http.commodityPrefixUrl;
const missionPrefixUrl = () => uni.$http.missionPrefixUrl;
export default {
	state:{
		name: 'user',
		userServiceProtocol: '',
		//
		regionList: [],
		addressList: [],
		myOrderListData: [],
		shouldRefreshMyOrderList: false,
		myOrderDetail: { orderItemList: [] },
		integralList: [],
	},
	getters: {
	},
	mutations: {
		[GET_USER_SERVICE_PROTOCOL] (state, { data }) {
			state.userServiceProtocol = data && data.setTxt;
		},
		[setRegionList] (state, { data }) {
			state.regionList = data;
		},
		[setUserAddressList] (state, { data, defaultStatus, isAdd, isDelete, isUpdate, id }) {
			if (isAdd) {
				let preList = state.addressList;
				if (defaultStatus === 1) {
					preList = preList.map(item => ({ ...item, defaultStatus: 0 }));
				}
				state.addressList = [...preList, data];
			} else if (isDelete) {
				state.addressList = state.addressList.filter(item => item.id !== id);
			} else if (isUpdate) {
				state.addressList = state.addressList.map(item => {
					if (item.id === id) {
						return { ...data };
					}
					return { ...item, defaultStatus: defaultStatus === 1 ? 0 : item.defaultStatus };
				});
			} else {
				state.addressList = data;
			}
		},
		[setMyOrderListData] (state, { data, isRefresh }) {
			if (isRefresh) {
				state.myOrderListData = data;
			} else {
				state.myOrderListData = [...state.myOrderListData, ...data];
			}
		},
		[setShouldRefreshMyOrderList] (state, { shouldRefreshMyOrderList }) {
			state.shouldRefreshMyOrderList = shouldRefreshMyOrderList;
		},
		[LOAD_MY_ORDER_DETAIL] (state, { data }) {
			state.myOrderDetail = data;
		},
		[INSERT_SHOP_COMMENT] (state, { data, params }) {
			// 评价成功将订单列表的状态改为已完成：3
			state.myOrderListData = state.myOrderListData.map(item => ({
				...item,
				status: item.id === params.orderItemId ? 3 : item.status,
			}));
		},
		[LOAD_INTEGRAL_LIST] (state, { data, isRefresh }) {
			if (isRefresh) {
				state.integralList = data;
			} else {
				state.integralList = [...state.integralList, ...data];
			}
		},
	},
	actions: {
		[UPLOAD_AVATAR] ({ commit }, params) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: 'https://dpc.way-s.cn/mvp/api/file/file/upload', //你的服务器地址
					filePath: params.path, //要上传文件资源的路径
					name: 'file', //文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
					formData: {
						file: params.path  //HTTP 请求中其他额外的参数比如 用户id
					},
					header: {
						'Content-Type': 'application/json',
						'Authorization': store.state.app.token || '',
					},
					success(res) {
						const { code = 200, data = {} } = JSON.parse(res.data);
						if (code === 200) {
							uni.showToast({
								title: '头像上传成功',
								icon: 'success',
							});
							resolve(data);
						} else {
							uni.showToast({
								title: '头像上传失败',
								icon: 'error',
							});
						}
					},
					error() {
						uni.showToast({
							title: '头像上传失败',
							icon: 'error',
						})
						resolve({});
					}
				})
			})
		},
		async [UODATE_MEMBER] ({ commit }, params) {
			try {
				uni.showToast({
					title: '编辑中',
					icon: 'loading',
				});
				const res = await uni.$http.post(prefixUrl() + '/sso/updateMember', params, true);
				if (res && res.code === 200) {
				}
				return res;
			} catch(err) {
				return err;
			}
		},
		async [GET_USER_SERVICE_PROTOCOL] ({ commit }, params) {
			try {
				const res = await uni.$http.get(shopPrefixUrl() + '/baseSet/getUserProtocol', params);
				if (res && res.code === 200) {
					const { data } = res;
					commit(GET_USER_SERVICE_PROTOCOL, { data })
				}
				return res;
			} catch (error) {
				console.error('GET_USER_SERVICE_PROTOCOL', error);
				return error;
			}
		},
		async [GET_REGION_LIST] ({ commit }, params) {
			try {
				const res = await uni.$http.get(shopPrefixUrl() + '/receiveAddress/getRgnOption', params);
				if (res && res.code === 200) {
					const { data = [] } = res;
					commit(setRegionList, { data })
				}
				return res;
			} catch (error) {
				console.error('GET_REGION_LIST', error);
				return error;
			}
		},
		async [GET_USER_ADDRESS_LIST] ({ commit }, params) {
			try {
				const res = await uni.$http.get(shopPrefixUrl() + '/receiveAddress/list', params);
				if (res && res.code === 200) {
					const { data = [] } = res;
					commit(setUserAddressList, { data })
				}
				return res;
			} catch (error) {
				console.error('GET_HOME_AD', error);
				return error;
			}
		},
		async [ADD_DELETE_USER_ADDRESS] ({ commit }, params) {
			try {
				const { isAdd, isDelete, id, ...rest } = params;
				if (isDelete) commit(setUserAddressList, { isAdd, isDelete, id });
				let res;
				if (isAdd) {
					res = await uni.$http.post(shopPrefixUrl() + '/receiveAddress/add', rest);
				} else {
					res = await uni.$http.get(shopPrefixUrl() + '/receiveAddress/delete', { id });
				}
				if (isAdd) {
					if (res && res.code === 200 && res.data) {
						commit(setUserAddressList, { data: res.data, defaultStatus: params.defaultStatus, isAdd, isDelete, id });
					} else {
						uni.showToast({
							title: '地址添加失败',
							duration: 2000,
							icon: 'none'
						});
					}
				}
				return res;
			} catch (error) {
				console.error('ADD_USER_ADDRESS', error);
				return error;
			}
		},
		async [UPDATE_USER_ADDRESS] ({ commit }, params) {
			try {
				const { id } = params;
				commit(setUserAddressList, { data: params, defaultStatus: params.defaultStatus, isUpdate: true, id });
				const res = await uni.$http.post(shopPrefixUrl() + '/receiveAddress/update', params);
				if (res && res.code !== 200) {
					uni.showToast({
						title: '地址更新失败',
						duration: 2000,
						icon: 'none'
					});
				}
				return res;
			} catch (error) {
				console.error('UPDATE_USER_ADDRESS', error);
				return error;
			}
		},
		async [LOAD_MY_ORDER_LIST] ({ commit }, params) {
			try {
				const { isRefresh, ...rest } = params;
				const res = await uni.$http.get(shopPrefixUrl() + '/order/list', rest);
				if (res && res.code === 200 && res.data) {
					const { data: { list = [] } } = res;
					commit(setMyOrderListData, { data: list || [], isRefresh })
				}
				return res;
			} catch (error) {
				console.error('LOAD_MY_ORDER_LIST', error);
				return error;
			}
		},
		async [LOAD_MY_ORDER_DETAIL] ({ commit }, params) {
			try {
				const res = await uni.$http.get(shopPrefixUrl() + '/order/detail', params);
				if (res && res.code === 200 && res.data) {
					const { data = {} } = res;
					commit(LOAD_MY_ORDER_DETAIL, { data })
				}
				return res;
			} catch (error) {
				console.error('LOAD_MY_ORDER_LIST', error);
				return error;
			}
		},
		async [USER_CONFIRM_RECERVE_ORDER] ({ commit }, params) { // 确认收货
			try {
				const res = await uni.$http.get(shopPrefixUrl() + '/order/confirmReceiveOrder', params);
				if (res && res.code === 200 && res.data) {
					const { data = {} } = res;
					commit(USER_CONFIRM_RECERVE_ORDER, { data })
				}
				return res;
			} catch (error) {
				console.error('USER_CONFIRM_RECERVE_ORDER', error);
				return error;
			}
		},
		async [INSERT_SHOP_COMMENT] ({ commit }, params) {
			try {
				const res = await uni.$http.post(shopPrefixUrl() + '/comment/addComment', params);
				if (res && res.code === 200) {
					// 评价成功将订单列表的状态改为已完成：3
					commit(INSERT_SHOP_COMMENT, { params });
				}
				return res;
			} catch (error) {
				console.error('UPDATE_USER_ADDRESS', error);
				return error;
			}
		},
		async [ADD_WX_SUBSCRIBE_MESSAGE] ({ commit }, params) {
			try {
				const res = await uni.$http.post(shopPrefixUrl() + '/subscribeMessage/addMessage', params);
				if (res && res.code === 200) {
					// 评价成功将订单列表的状态改为已完成：3
				}
				return res;
			} catch (error) {
				console.error('ADD_WX_SUBSCRIBE_MESSAGE', error);
				return error;
			}
		},
		async [LOAD_INTEGRAL_LIST] ({ commit }, params) {
			try {
				const { isRefresh, ...rest } = params;
				const res = await uni.$http.post(missionPrefixUrl() + '/memberIntegration/getMemberStreamList', rest);
				// const res = await uni.$http.post('http://10.10.25.84:8087' + '/memberIntegration/getMemberStreamList', rest);
				if (res && res.code === 200 && res.data) {
					const { data: { list = [] } } = res;
					commit(LOAD_INTEGRAL_LIST, { data: list || [], isRefresh })
				}
				return res;
			} catch (error) {
				console.error('LOAD_INTEGRAL_LIST', error);
				return error;
			}
		},
	}
}
